<?php

namespace Orgs\Controller;

use Doc\Model\ApplyOrgModel;
use Doc\Model\ArticleModel;
use Doc\Model\ClassModel;
use Doc\Model\LogModel;
use Doc\Model\MsgModel;
use Doc\Model\OrgDocModel;
use Doc\Model\OrgModel;
use Doc\Model\UserDocModel;
use Doc\Model\UserOrgModel;
use Home\Controller\BaseController;

class IndexController extends BaseController
{

    /**
     * 团体展示：展示团体的相关描述以及团体所维护的文档列表
     */
    public function index(){
        echo 1;
        exit;
        $oid = I('get.oid', 0);
        $org = null;
        if(!$oid || !($org = OrgModel::getOrgById($oid))){
            $this->error('数据异常，请稍后再试！');
        }
        $docs = OrgDocModel::getOrgDocsInfo($oid);
        $this->assign('org', $org);
        $this->assign('auth', UserOrgModel::checkOrgManager(UID, $oid, true));
        $this->assign('docs', $docs);
        $this->assign('title', $org['name'].' - 团体');
        $this->assign('description', '团体'.$org['name'].'的团体展示,'.$org['desc']);
        $this->display();
    }

    /**
     * 修改团体信息
     */
    public function set(){
        $oid = I('get.oid', 0);
        if(!UID){
            $this->error('您需要先登录账号！',U('/login@wooo.wang'));
        }
        $org = null;
        if(!$oid || !($org = OrgModel::getOrgById($oid))){
            $this->error('访问异常，请稍后再试！');
        }
        if(!UserOrgModel::checkOrgManager(UID, $oid, true)){
            $this->error('您没有操作权限！');
        }
        if(IS_POST){
            $name = I('post.name', '');
            $bbsName = I('post.bbsname', '');
            $desc = I('post.desc', '');
            $cate = I('post.cateid', 0);
            if(!checkStrLength($name, 2) || !checkStrLength($bbsName, 2) || !$desc){
                $this->error('您提交的团体数据有误，请您重新提交！');
            }
            $data = array(
                'name'  => $name,
                'bbsname' => $bbsName,
                'desc'  => $desc,
                'class' => $cate
            );
            $result = OrgModel::updateOrg($oid, $data);
            if(!$result){
                $this->error('修改团体信息失败，请稍后再试！');
            }
            $this->success('团体设置成功！', U('/org/'.$oid));
        }else{
            $this->assign('cate', ClassModel::getCreateClass());
            $this->assign('org', $org);
            $this->assign('title', $org['name'].' - 团体设置');
            $this->assign('description', '设置'.$org['name'].'团体的相关信息！'.$org['desc']);
            $this->display();
        }
    }

    /**
     * 团体管理：展示团体的管理人员
     */
    public function manage(){
        $oid = I('get.oid', 0);
        $org = null;
        if(!$oid || !($org = OrgModel::getOrgById($oid))){
            $this->error('访问异常，请稍后再试！');
        }
        $isManager = UID ? UserOrgModel::checkOrgManager(UID, $oid) : false;
        $isSuper = $isManager ? UserOrgModel::checkOrgManager(UID, $oid, true) : false;
        if(IS_POST){
            $type = I('post.type', 0);
            $content = I('post.content', '');
            if(!UID){
                $this->error('需要登陆');
            }
            if(!$content){
                $this->error('参数错误');
            }
            if($type == 1){
                if($isManager){
                    $this->error('您已经是管理员了，请勿重复申请');
                }
            }else if($type == 2){
                if(!$isManager){
                    $this->error('您还不是管理员，暂不能申请超级管理员');
                }else if($isSuper){
                    $this->error('您已经是超级管理员了，请勿重复申请');
                }
            }else if($type == -1){
                if(!$isManager){
                    $this->error('您还不是管理员，因此不能辞职');
                }
            }else{
                $this->error('参数错误');
            }
            if(ApplyOrgModel::addApplyOrg(UID, $oid, $type, $content)){
                $this->success('您已成功提交你的申请，请等待审核后的通知！', U('/alist/'.$oid), 4);
            }
            $this->error('申请提交失败，请稍后再试');
        }else{
            $admin = UserOrgModel::getOrgUsersInfo($oid, true);
            $manager = UserOrgModel::getOrgUsersInfo($oid, false);
            $this->assign('auth', $isSuper);
            $this->assign('isManager', $isManager);
            $this->assign('admin', $admin);
            $this->assign('manager', $manager);
            $this->assign('org', $org);
            $this->assign('title', $org['name'].' - 团体管理');
            $this->assign('description', $org['name'].'的团体管理，展示'.$org['name'].'团体的管理员和超级管理员信息，以及申请成为管理员和辞职！'.$org['desc']);
            $this->display();
        }
    }

    /**
     * 团体的管理员申请页面
     */
    public function alist(){
        $oid = I('get.oid', 0);
        $p = I('get.p', 1);
        $pcount = 10;
        $org = null;
        if(!$oid || !($org = OrgModel::getOrgById($oid))){
            $this->error('访问异常，请稍后再试！');
        }
        $isSuper = UID ? UserOrgModel::checkOrgManager(UID, $oid, true) : false;
        $data = ApplyOrgModel::getApplyList($oid, $p, $pcount);
        $this->assign('auth', $isSuper);
        $this->assign('list', $data['list']);
        $this->assign('page', page($data['count'], $pcount, $p));
        $this->assign('org', $org);
        $this->assign('title', $org['name'].' - 申请审核'.($p === 1 ? '' : '[第'.$p.'页]'));
        $this->assign('description', $org['name'].'团体的'.($p === 1 ? '' : '[第'.$p.'页]').'申请列表，包括申请成为管理员和超级管理员，以及申请辞职，超级管理员可以进行审核!'.$org['desc']);
        $this->display();
    }

    /**
     * ajax 超级管理员处理管理员申请与辞职记录
     */
    public function dealapply(){
        if(!UID){
            json(204, '需要登陆');
        }
        $aid = I('post.aid', 0);
        $result = I('post.type', 0);
        $apply = I('post.content', '');
        $record = $aid ? ApplyOrgModel::getApplyOrg($aid) : null;
        if(!$record || !($result == ApplyOrgModel::PASSED || $result == ApplyOrgModel::REJECTED)){
            json(204, '参数错误');
        }
        $org = null;
        if(!UserOrgModel::checkOrgManager(UID, $record['oid'], true)){
            json(204, '您没有操作权限');
        }
        if($result == ApplyOrgModel::PASSED && $record['type'] == ApplyOrgModel::TO_BYE && UserOrgModel::checkOnlySuper($record['uid'], $record['oid'])){
            json(204, '团体的最后一个超级管理员不可辞职');
        }
        $res = ApplyOrgModel::dealApply(UID, $record, $result, $apply);
        if(false !== $res){
            json(200);
        }
        json(204, '处理申请记录失败，请稍后再试');
    }

    /**
     * 团体下各文档的审阅列表记录
     */
    public function elist(){
        $oid = I('get.oid', 0);
        $did = I('get.did', 0);
        $p = I('get.pid', 1);
        $pcount = 10;
        $org = null;
        if(!$oid || !($org = OrgModel::getOrgById($oid))){
            $this->error('数据异常，请稍后再试！');
        }
        $docs = OrgDocModel::getOrgDocsInfo($oid);
        $articles = $did ? ArticleModel::getArticleList($did, $p, $pcount) : array();
        $this->assign('auth', UserOrgModel::checkOrgManager(UID, $oid, true));
        $this->assign('docs', $docs);
        $this->assign('did', $did);
        $this->assign('org', $org);
        $this->assign('list', $articles['list']);
        $this->assign('page', page($articles['count'], $pcount, $p));
        $this->assign('title', $org['name'].' - 审阅'.($did ? '[第'.$did.'-'.$p.'页]' : ''));
        $this->assign('description', '团体'.$org['name'].'的'.($did ? '[第'.$did.'-'.$p.'页]' : '').'审阅记录，展示团体下所有文档的所有审阅信息，用户编辑、修改文档之后会展示到该页面！'.$org['desc']);
        $this->display();
    }

    /**
     * 展示团体的贡献度日志记录
     */
    public function log(){
        $oid = I('get.oid', 0);
        $p = I('get.p', 1);    //页数
        $pcount = 15;          //每页显示数量
        $org = null;
        if(!$oid || !($org = OrgModel::getOrgById($oid))){
            $this->error('访问异常，请稍后再试！');
        }
        $result = LogModel::getLogHtml($oid, $p, $pcount);
        $this->assign('org', $org);
        $this->assign('html', $result['list']);
        $this->assign('page', page($result['count'], $pcount, $p));
        $this->assign('auth', UserOrgModel::checkOrgManager(UID, $oid, true));
        $this->assign('collets', UserDocModel::getUserDocCount(UID) ? : '');
        $this->assign('title', $org['name'].' - 贡献日志'.($p == 1 ? '' : '[第'.$p.'页]'));
        $this->assign('description', '团体'.$org['name'].'的'.($p == 1 ? '所有' : '[第'.$p.'页]').'贡献度日志，清晰明了的展示团体的贡献度收支明系！'.$org['desc']);
        $this->display();
    }








    // 以下方法已被弃用
    public function invite(){
        $mid=I('get.m',0);
        if(UID==0){
            $this->error('您需要登录账号之后才可进行操作！',U('home/index/login'));
        }
        if($mid){
            $manage=M('Manage')->where(array('id'=>$mid))->field('id,org,desc,editor')->find();
            if($manage&&in_array(UID, explode(',', $manage['editor']))){
                if(IS_POST){
                    $email=I('post.email','');
                    if(preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $email)){
                        $obj=M('User')->where(array('email'=>$email))->field('id,nick')->find();
                        if($obj&&!in_array($obj['id'], explode(',', $manage['editor']))){
                            $title = '我网-执笔邀请';
                            $content='<h3 status="text-align:center;">邀请函</h3><p>尊敬的'.$obj['nick'].'，您好！<br>我网 - '.$manage['org'].' 团体邀请您成为执笔大人，执笔拥有权限包括但不限于：自由修改团体所属文档、建立新的团体所属文档、管理团体所属问答、邀请新的执笔！希望您能加入我们，共同协作开发团体所属文档！<br>如果您愿意成为团体的执笔大人，您可以点击下面的链接(或将网址复制到浏览器中打开)：<br><a href="http://www.inets.wang/tell/manage/dealinvite/m/'.$manage['id'].'/u/'.$obj['id'].'/token/'.md5($manage['id'].'invite'.$obj['id'].'becomeaeditor').'.html">http://www.inets.wang/tell/manage/dealinvite/m/'.$manage['id'].'/u/'.$obj['id'].'/token/'.md5($manage['id'].'invite'.$obj['id'].'becomeaeditor').'.html</a></p>';
                            if(SendMail($email,$title,$content)){
                                $this->success('您已成功邀请'.$obj['nick'].'['.$email.']！',U('tell/manage/show/m/'.$mid));
                            }else{
                                $this->error("抱歉,在邀请过程中出现错误，请重新再试!",U('tell/manage/show/m/'.$mid));
                            }
                        }else{
                            $this->error('抱歉，您所邀请的用户已为执笔或暂未加入我网！');
                        }
                    }else{
                        $this->error('您所输入的邮箱格式不正确，请重新输入！');
                    }
                }else{
                    $this->assign('manage',$manage);
                    $this->assign('title','邀请执笔');
                    $this->assign('description','为团体'.$manage['org'].'邀请更多的执笔');
                    $this->display();
                }
            }else{
                $this->error('抱歉，当前操作出现错误！！！');
            }
        }else{
            $this->error('当前操作出现错误！！！');
        }
    }
    public function dealinvite(){
        $mid=I('get.m',0);
        $uid=I('get.u',0);
        $token=I('get.token','');
        if(UID==0){
            $this->error('您需要登录账号之后才可进行操作！',U('home/index/login/url/'.str_replace('%','_',urlencode('http://www.inets.wang/tell/manage/dealinvite/m/'.$mid.'/u/'.$uid.'/token/'.$token))));
        }
        if($token==md5($mid.'invite'.$uid.'becomeaeditor')){
            $manage=M('User')->where(array('id'=>$uid))->getField('manage');
            if(!in_array($mid, explode(',', $manage))){
                $newManage=$manage?$manage.','.$mid:$mid;
                $editor=M('Manage')->where(array('id'=>$mid))->getField('editor');
                M('User')->where(array('id'=>$uid))->setField('manage',$newManage);
                M('Manage')->where(array('id'=>$mid))->setField('editor',$editor?$editor.','.$uid:$uid);
                updateSession('manage',$newManage);
                $this->success('恭喜您成为我网执笔,希望以后我们合作愉快！',U('tell/manage/show/m/'.$mid),5);
            }else{
                $this->success('您已成为我网执笔！',U('tell/manage/show/m/'.$mid));
            }
        }else{
            $this->error('参数验证失败，请联系管理员！',U('tell/index/index'));
        }
    }

}